package ru.stepuk.modeller.buffers;

import java.util.Deque;
import java.util.LinkedList;
import java.util.ListIterator;
import ru.stepuk.modeller.PriorityRequest;
import ru.stepuk.modeller.Request;

/**
 *
 * @author ivan
 */
public class PriorityQueue extends Buffer {

    public PriorityQueue(int capacity) {
        this.capacity = capacity;
        container = new LinkedList<Request>();
    }

    @Override
    public void putRequest(Request request) throws FullQueueException {

        if (!(request instanceof PriorityRequest)) {
            throw new IllegalArgumentException();
        }

        if (!hasFreeSpace()) {
            throw new FullQueueException();
        }

        PriorityRequest r = (PriorityRequest) request;

        if (isEmpty() ||
                r.getPriority() <= ((PriorityRequest) ((Deque) container).peekLast()).getPriority()) {
            container.add(request);
            return;
        }

        ListIterator<Request> it = container.listIterator();
        while (it.hasNext()) {
            if (r.getPriority() > ((PriorityRequest) it.next()).getPriority()) {
                container.add(it.previousIndex(), request);
                return;
            }
        }
    }

    @Override
    public PriorityRequest getRequest() {
        return (PriorityRequest) ((Deque) container).pollFirst();
    }
}
